package com.academic.system.controller;

import com.academic.system.model.*;
import com.academic.system.repository.*;
import com.academic.system.security.UserDetailsImpl;
import com.academic.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

/**
 * 统一成果管理控制器
 */
@RestController
@RequestMapping("/api/achievements")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AchievementController {

    @Autowired
    private PaperRepository paperRepository;
    
    @Autowired
    private VerticalProjectRepository verticalProjectRepository;
    
    @Autowired
    private HorizontalProjectRepository horizontalProjectRepository;
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取当前用户的所有成果
     */
    @GetMapping("/my")
    @PreAuthorize("hasRole('STUDENT') or hasRole('TEACHER')")
    public ResponseEntity<?> getMyAchievements(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type) {
        
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        List<Map<String, Object>> allAchievements = new ArrayList<>();
        
        // 根据类型筛选
        if (type == null || "论文".equals(type)) {
            List<Paper> papers = status != null ? 
                paperRepository.findByCreatorIdAndStatus(userDetails.getId(), status) :
                paperRepository.findByCreatorId(userDetails.getId());
            
            papers.forEach(paper -> allAchievements.add(convertPaperToDto(paper)));
        }
        
        if (type == null || "纵向课题".equals(type)) {
            List<VerticalProject> verticalProjects = status != null ?
                verticalProjectRepository.findByCreatorIdAndStatus(userDetails.getId(), status) :
                verticalProjectRepository.findByCreatorId(userDetails.getId());
            
            verticalProjects.forEach(project -> allAchievements.add(convertVerticalProjectToDto(project)));
        }
        
        if (type == null || "横向课题".equals(type)) {
            List<HorizontalProject> horizontalProjects = status != null ?
                horizontalProjectRepository.findByCreatorIdAndStatus(userDetails.getId(), status) :
                horizontalProjectRepository.findByCreatorId(userDetails.getId());
            
            horizontalProjects.forEach(project -> allAchievements.add(convertHorizontalProjectToDto(project)));
        }
        
        return ResponseEntity.ok(allAchievements);
    }
    
    /**
     * 获取所有成果（教师端管理用）
     */
    @GetMapping("/all")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> getAllAchievements(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Integer studentId) {
        
        List<Map<String, Object>> allAchievements = new ArrayList<>();
        
        // 获取论文
        if (type == null || "论文".equals(type)) {
            List<Paper> papers;
            if (studentId != null && status != null) {
                papers = paperRepository.findByCreatorIdAndStatus(studentId, status);
            } else if (studentId != null) {
                papers = paperRepository.findByCreatorId(studentId);
            } else if (status != null) {
                papers = paperRepository.findByApprovalStatus(status);
            } else {
                papers = paperRepository.findAll();
            }
            papers.forEach(paper -> allAchievements.add(convertPaperToDto(paper)));
        }
        
        // 获取纵向课题
        if (type == null || "纵向课题".equals(type)) {
            List<VerticalProject> verticalProjects;
            if (studentId != null && status != null) {
                verticalProjects = verticalProjectRepository.findByCreatorIdAndStatus(studentId, status);
            } else if (studentId != null) {
                verticalProjects = verticalProjectRepository.findByCreatorId(studentId);
            } else if (status != null) {
                verticalProjects = verticalProjectRepository.findByApprovalStatus(status);
            } else {
                verticalProjects = verticalProjectRepository.findAll();
            }
            verticalProjects.forEach(project -> allAchievements.add(convertVerticalProjectToDto(project)));
        }
        
        // 获取横向课题
        if (type == null || "横向课题".equals(type)) {
            List<HorizontalProject> horizontalProjects;
            if (studentId != null && status != null) {
                horizontalProjects = horizontalProjectRepository.findByCreatorIdAndStatus(studentId, status);
            } else if (studentId != null) {
                horizontalProjects = horizontalProjectRepository.findByCreatorId(studentId);
            } else if (status != null) {
                horizontalProjects = horizontalProjectRepository.findByApprovalStatus(status);
            } else {
                horizontalProjects = horizontalProjectRepository.findAll();
            }
            horizontalProjects.forEach(project -> allAchievements.add(convertHorizontalProjectToDto(project)));
        }
        
        return ResponseEntity.ok(allAchievements);
    }
    
    /**
     * 创建新成果
     */
    @PostMapping
    @PreAuthorize("hasRole('STUDENT') or hasRole('TEACHER')")
    public ResponseEntity<?> createAchievement(@RequestBody Map<String, Object> request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        User creator = userService.findById(userDetails.getId());
        if (creator == null) {
            return ResponseEntity.badRequest().body(Map.of("message", "用户信息不存在"));
        }
        
        String type = (String) request.get("type");
        
        try {
            Map<String, Object> result;
            
            switch (type) {
                case "论文":
                    result = createPaper(request, creator);
                    break;
                case "纵向课题":
                    result = createVerticalProject(request, creator);
                    break;
                case "横向课题":
                    result = createHorizontalProject(request, creator);
                    break;
                default:
                    return ResponseEntity.badRequest().body(Map.of("message", "不支持的成果类型"));
            }
            
            return ResponseEntity.status(HttpStatus.CREATED).body(result);
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("message", "创建失败: " + e.getMessage()));
        }
    }
    
    private Map<String, Object> createPaper(Map<String, Object> request, User creator) {
        Paper paper = new Paper();
        paper.setPaperTitle((String) request.get("title"));
        paper.setJournal((String) request.get("journal"));
        paper.setIssueNumber((String) request.get("issueNumber"));
        paper.setVolumeNumber((String) request.get("volumeNumber"));
        paper.setPageNumber((String) request.get("pageNumber"));
        paper.setIndexLevel((String) request.get("indexLevel"));
        paper.setAuthors((String) request.get("authors"));
        paper.setFirstAuthor((String) request.get("firstAuthor"));
        paper.setCorrespondingAuthor((String) request.get("correspondingAuthor"));
        
        if (request.get("publicationDate") != null) {
            paper.setPublicationDate(LocalDate.parse((String) request.get("publicationDate")));
        }
        
        if (request.get("impactFactor") != null) {
            paper.setImpactFactor(new BigDecimal(request.get("impactFactor").toString()));
        }
        
        paper.setPaperLink((String) request.get("paperLink"));
        paper.setCreator(creator);
        
        paperRepository.insert(paper);
        return convertPaperToDto(paper);
    }
    
    private Map<String, Object> createVerticalProject(Map<String, Object> request, User creator) {
        VerticalProject project = new VerticalProject();
        project.setProjectName((String) request.get("title"));
        project.setProjectNumber((String) request.get("projectNumber"));
        project.setProjectCode((String) request.get("projectCode"));
        project.setProjectLevel((String) request.get("projectLevel"));
        
        if (request.get("totalAmount") != null) {
            project.setTotalAmount(new BigDecimal(request.get("totalAmount").toString()));
        }
        
        project.setApprovalDepartment((String) request.get("approvalDepartment"));
        project.setProjectType((String) request.get("projectType"));
        project.setDuration((String) request.get("duration"));
        project.setPaymentRecord((String) request.get("paymentRecord"));
        project.setParticipants((String) request.get("participants"));
        project.setProjectLeader((String) request.get("projectLeader"));
        project.setFinancialAccount((String) request.get("financialAccount"));
        
        if (request.get("completionDate") != null) {
            project.setCompletionDate(LocalDate.parse((String) request.get("completionDate")));
        }
        
        project.setCreator(creator);
        
        verticalProjectRepository.insert(project);
        return convertVerticalProjectToDto(project);
    }
    
    private Map<String, Object> createHorizontalProject(Map<String, Object> request, User creator) {
        HorizontalProject project = new HorizontalProject();
        project.setProjectName((String) request.get("title"));
        project.setContractNumber((String) request.get("contractNumber"));
        
        if (request.get("contractAmount") != null) {
            project.setContractAmount(new BigDecimal(request.get("contractAmount").toString()));
        }
        
        project.setClientName((String) request.get("clientName"));
        project.setProjectLeader((String) request.get("projectLeader"));
        project.setExecutiveLeader((String) request.get("executiveLeader"));
        project.setDuration((String) request.get("duration"));
        project.setPaymentRecord((String) request.get("paymentRecord"));
        project.setParticipants((String) request.get("participants"));
        project.setFinancialAccount((String) request.get("financialAccount"));
        
        if (request.get("completionDate") != null) {
            project.setCompletionDate(LocalDate.parse((String) request.get("completionDate")));
        }
        
        project.setCreator(creator);
        
        horizontalProjectRepository.insert(project);
        return convertHorizontalProjectToDto(project);
    }
    
    private Map<String, Object> convertPaperToDto(Paper paper) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", paper.getId());
        dto.put("title", paper.getPaperTitle());
        dto.put("type", "论文");
        dto.put("status", convertStatus(paper.getApprovalStatus()));
        dto.put("createdAt", paper.getSubmissionDate().toString());
        
        // 论文特有字段
        dto.put("journal", paper.getJournal());
        dto.put("issueNumber", paper.getIssueNumber());
        dto.put("volumeNumber", paper.getVolumeNumber());
        dto.put("pageNumber", paper.getPageNumber());
        dto.put("indexLevel", paper.getIndexLevel());
        dto.put("authors", paper.getAuthors());
        dto.put("firstAuthor", paper.getFirstAuthor());
        dto.put("correspondingAuthor", paper.getCorrespondingAuthor());
        dto.put("publicationDate", paper.getPublicationDate() != null ? paper.getPublicationDate().toString() : null);
        dto.put("impactFactor", paper.getImpactFactor());
        dto.put("paperLink", paper.getPaperLink());
        dto.put("approvalComment", paper.getApprovalComment());
        
        if (paper.getCreator() != null) {
            dto.put("creator", Map.of("id", paper.getCreator().getId(), "realName", paper.getCreator().getRealName()));
        }
        
        return dto;
    }
    
    private Map<String, Object> convertVerticalProjectToDto(VerticalProject project) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", project.getId());
        dto.put("title", project.getProjectName());
        dto.put("type", "纵向课题");
        dto.put("status", convertStatus(project.getApprovalStatus()));
        dto.put("createdAt", project.getSubmissionDate().toString());
        
        // 纵向课题特有字段
        dto.put("projectNumber", project.getProjectNumber());
        dto.put("projectCode", project.getProjectCode());
        dto.put("projectLevel", project.getProjectLevel());
        dto.put("totalAmount", project.getTotalAmount());
        dto.put("approvalDepartment", project.getApprovalDepartment());
        dto.put("projectType", project.getProjectType());
        dto.put("duration", project.getDuration());
        dto.put("paymentRecord", project.getPaymentRecord());
        dto.put("participants", project.getParticipants());
        dto.put("projectLeader", project.getProjectLeader());
        dto.put("financialAccount", project.getFinancialAccount());
        dto.put("completionDate", project.getCompletionDate() != null ? project.getCompletionDate().toString() : null);
        dto.put("approvalComment", project.getApprovalComment());
        
        if (project.getCreator() != null) {
            dto.put("creator", Map.of("id", project.getCreator().getId(), "realName", project.getCreator().getRealName()));
        }
        
        return dto;
    }
    
    private Map<String, Object> convertHorizontalProjectToDto(HorizontalProject project) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", project.getId());
        dto.put("title", project.getProjectName());
        dto.put("type", "横向课题");
        dto.put("status", convertStatus(project.getApprovalStatus()));
        dto.put("createdAt", project.getSubmissionDate().toString());
        
        // 横向课题特有字段
        dto.put("contractNumber", project.getContractNumber());
        dto.put("contractAmount", project.getContractAmount());
        dto.put("clientName", project.getClientName());
        dto.put("projectLeader", project.getProjectLeader());
        dto.put("executiveLeader", project.getExecutiveLeader());
        dto.put("duration", project.getDuration());
        dto.put("paymentRecord", project.getPaymentRecord());
        dto.put("participants", project.getParticipants());
        dto.put("financialAccount", project.getFinancialAccount());
        dto.put("completionDate", project.getCompletionDate() != null ? project.getCompletionDate().toString() : null);
        dto.put("approvalComment", project.getApprovalComment());
        
        if (project.getCreator() != null) {
            dto.put("creator", Map.of("id", project.getCreator().getId(), "realName", project.getCreator().getRealName()));
        }
        
        return dto;
    }
    
    private String convertStatus(String dbStatus) {
        switch (dbStatus) {
            case "pending": return "待审核";
            case "approved": return "已通过";
            case "rejected": return "已拒绝";
            default: return dbStatus;
        }
    }
    
    /**
     * 获取成果统计信息
     */
    @GetMapping("/stats")
    @PreAuthorize("hasRole('STUDENT') or hasRole('TEACHER')")
    public ResponseEntity<?> getAchievementStats() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        Map<String, Integer> stats = new HashMap<>();
        
        // 统计各类型成果数量
        int paperTotal = paperRepository.countByCreatorId(userDetails.getId());
        int paperApproved = paperRepository.countByCreatorIdAndStatus(userDetails.getId(), "approved");
        int paperPending = paperRepository.countByCreatorIdAndStatus(userDetails.getId(), "pending");
        int paperRejected = paperRepository.countByCreatorIdAndStatus(userDetails.getId(), "rejected");
        
        int verticalTotal = verticalProjectRepository.countByCreatorId(userDetails.getId());
        int verticalApproved = verticalProjectRepository.countByCreatorIdAndStatus(userDetails.getId(), "approved");
        int verticalPending = verticalProjectRepository.countByCreatorIdAndStatus(userDetails.getId(), "pending");
        int verticalRejected = verticalProjectRepository.countByCreatorIdAndStatus(userDetails.getId(), "rejected");
        
        int horizontalTotal = horizontalProjectRepository.countByCreatorId(userDetails.getId());
        int horizontalApproved = horizontalProjectRepository.countByCreatorIdAndStatus(userDetails.getId(), "approved");
        int horizontalPending = horizontalProjectRepository.countByCreatorIdAndStatus(userDetails.getId(), "pending");
        int horizontalRejected = horizontalProjectRepository.countByCreatorIdAndStatus(userDetails.getId(), "rejected");
        
        stats.put("total", paperTotal + verticalTotal + horizontalTotal);
        stats.put("approved", paperApproved + verticalApproved + horizontalApproved);
        stats.put("pending", paperPending + verticalPending + horizontalPending);
        stats.put("rejected", paperRejected + verticalRejected + horizontalRejected);
        
        return ResponseEntity.ok(stats);
    }
    
    /**
     * 根据ID获取成果详情
     */
    @GetMapping("/{type}/{id}")
    @PreAuthorize("hasRole('STUDENT') or hasRole('TEACHER')")
    public ResponseEntity<?> getAchievementById(@PathVariable String type, @PathVariable Integer id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        try {
            Map<String, Object> result;
            
            switch (type) {
                case "论文":
                    Paper paper = paperRepository.findById(id);
                    if (paper == null) {
                        return ResponseEntity.notFound().build();
                    }
                    if (!paper.getCreator().getId().equals(userDetails.getId())) {
                        return ResponseEntity.status(HttpStatus.FORBIDDEN)
                            .body(Map.of("message", "无权访问他人的成果"));
                    }
                    result = convertPaperToDto(paper);
                    break;
                case "纵向课题":
                    VerticalProject verticalProject = verticalProjectRepository.findById(id);
                    if (verticalProject == null) {
                        return ResponseEntity.notFound().build();
                    }
                    if (!verticalProject.getCreator().getId().equals(userDetails.getId())) {
                        return ResponseEntity.status(HttpStatus.FORBIDDEN)
                            .body(Map.of("message", "无权访问他人的成果"));
                    }
                    result = convertVerticalProjectToDto(verticalProject);
                    break;
                case "横向课题":
                    HorizontalProject horizontalProject = horizontalProjectRepository.findById(id);
                    if (horizontalProject == null) {
                        return ResponseEntity.notFound().build();
                    }
                    if (!horizontalProject.getCreator().getId().equals(userDetails.getId())) {
                        return ResponseEntity.status(HttpStatus.FORBIDDEN)
                            .body(Map.of("message", "无权访问他人的成果"));
                    }
                    result = convertHorizontalProjectToDto(horizontalProject);
                    break;
                default:
                    return ResponseEntity.badRequest().body(Map.of("message", "不支持的成果类型"));
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("message", "获取成果详情失败: " + e.getMessage()));
        }
    }
    
    /**
     * 更新成果
     */
    @PutMapping("/{type}/{id}")
    @PreAuthorize("hasRole('STUDENT') or hasRole('TEACHER')")
    public ResponseEntity<?> updateAchievement(@PathVariable String type, @PathVariable Integer id, 
                                             @RequestBody Map<String, Object> request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        try {
            Map<String, Object> result;
            
            switch (type) {
                case "论文":
                    result = updatePaper(id, request, userDetails.getId());
                    break;
                case "纵向课题":
                    result = updateVerticalProject(id, request, userDetails.getId());
                    break;
                case "横向课题":
                    result = updateHorizontalProject(id, request, userDetails.getId());
                    break;
                default:
                    return ResponseEntity.badRequest().body(Map.of("message", "不支持的成果类型"));
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("message", "更新成果失败: " + e.getMessage()));
        }
    }
    
    /**
     * 删除成果
     */
    @DeleteMapping("/{type}/{id}")
    @PreAuthorize("hasRole('STUDENT') or hasRole('TEACHER')")
    public ResponseEntity<?> deleteAchievement(@PathVariable String type, @PathVariable Integer id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        try {
            switch (type) {
                case "论文":
                    Paper paper = paperRepository.findById(id);
                    if (paper == null) {
                        return ResponseEntity.notFound().build();
                    }
                    if (!paper.getCreator().getId().equals(userDetails.getId())) {
                        return ResponseEntity.status(HttpStatus.FORBIDDEN)
                            .body(Map.of("message", "无权删除他人的成果"));
                    }
                    if (!"pending".equals(paper.getApprovalStatus())) {
                        return ResponseEntity.badRequest()
                            .body(Map.of("message", "只有待审核状态的成果才能删除"));
                    }
                    paperRepository.deleteById(id);
                    break;
                case "纵向课题":
                    VerticalProject verticalProject = verticalProjectRepository.findById(id);
                    if (verticalProject == null) {
                        return ResponseEntity.notFound().build();
                    }
                    if (!verticalProject.getCreator().getId().equals(userDetails.getId())) {
                        return ResponseEntity.status(HttpStatus.FORBIDDEN)
                            .body(Map.of("message", "无权删除他人的成果"));
                    }
                    if (!"pending".equals(verticalProject.getApprovalStatus())) {
                        return ResponseEntity.badRequest()
                            .body(Map.of("message", "只有待审核状态的成果才能删除"));
                    }
                    verticalProjectRepository.deleteById(id);
                    break;
                case "横向课题":
                    HorizontalProject horizontalProject = horizontalProjectRepository.findById(id);
                    if (horizontalProject == null) {
                        return ResponseEntity.notFound().build();
                    }
                    if (!horizontalProject.getCreator().getId().equals(userDetails.getId())) {
                        return ResponseEntity.status(HttpStatus.FORBIDDEN)
                            .body(Map.of("message", "无权删除他人的成果"));
                    }
                    if (!"pending".equals(horizontalProject.getApprovalStatus())) {
                        return ResponseEntity.badRequest()
                            .body(Map.of("message", "只有待审核状态的成果才能删除"));
                    }
                    horizontalProjectRepository.deleteById(id);
                    break;
                default:
                    return ResponseEntity.badRequest().body(Map.of("message", "不支持的成果类型"));
            }
            
            return ResponseEntity.ok(Map.of("message", "删除成功"));
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("message", "删除成果失败: " + e.getMessage()));
        }
    }
    
    private Map<String, Object> updatePaper(Integer id, Map<String, Object> request, Integer userId) {
        Paper paper = paperRepository.findById(id);
        if (paper == null) {
            throw new RuntimeException("论文不存在");
        }
        if (!paper.getCreator().getId().equals(userId)) {
            throw new RuntimeException("无权修改他人的成果");
        }
        if (!"pending".equals(paper.getApprovalStatus())) {
            throw new RuntimeException("只有待审核状态的成果才能修改");
        }
        
        // 更新字段
        if (request.containsKey("title")) {
            paper.setPaperTitle((String) request.get("title"));
        }
        if (request.containsKey("journal")) {
            paper.setJournal((String) request.get("journal"));
        }
        if (request.containsKey("issueNumber")) {
            paper.setIssueNumber((String) request.get("issueNumber"));
        }
        if (request.containsKey("volumeNumber")) {
            paper.setVolumeNumber((String) request.get("volumeNumber"));
        }
        if (request.containsKey("pageNumber")) {
            paper.setPageNumber((String) request.get("pageNumber"));
        }
        if (request.containsKey("indexLevel")) {
            paper.setIndexLevel((String) request.get("indexLevel"));
        }
        if (request.containsKey("authors")) {
            paper.setAuthors((String) request.get("authors"));
        }
        if (request.containsKey("firstAuthor")) {
            paper.setFirstAuthor((String) request.get("firstAuthor"));
        }
        if (request.containsKey("correspondingAuthor")) {
            paper.setCorrespondingAuthor((String) request.get("correspondingAuthor"));
        }
        if (request.containsKey("publicationDate") && request.get("publicationDate") != null) {
            paper.setPublicationDate(LocalDate.parse((String) request.get("publicationDate")));
        }
        if (request.containsKey("impactFactor") && request.get("impactFactor") != null) {
            paper.setImpactFactor(new BigDecimal(request.get("impactFactor").toString()));
        }
        if (request.containsKey("paperLink")) {
            paper.setPaperLink((String) request.get("paperLink"));
        }
        
        paperRepository.update(paper);
        return convertPaperToDto(paper);
    }
    
    private Map<String, Object> updateVerticalProject(Integer id, Map<String, Object> request, Integer userId) {
        VerticalProject project = verticalProjectRepository.findById(id);
        if (project == null) {
            throw new RuntimeException("纵向课题不存在");
        }
        if (!project.getCreator().getId().equals(userId)) {
            throw new RuntimeException("无权修改他人的成果");
        }
        if (!"pending".equals(project.getApprovalStatus())) {
            throw new RuntimeException("只有待审核状态的成果才能修改");
        }
        
        // 更新字段
        if (request.containsKey("title")) {
            project.setProjectName((String) request.get("title"));
        }
        if (request.containsKey("projectNumber")) {
            project.setProjectNumber((String) request.get("projectNumber"));
        }
        if (request.containsKey("projectCode")) {
            project.setProjectCode((String) request.get("projectCode"));
        }
        if (request.containsKey("projectLevel")) {
            project.setProjectLevel((String) request.get("projectLevel"));
        }
        if (request.containsKey("totalAmount") && request.get("totalAmount") != null) {
            project.setTotalAmount(new BigDecimal(request.get("totalAmount").toString()));
        }
        if (request.containsKey("approvalDepartment")) {
            project.setApprovalDepartment((String) request.get("approvalDepartment"));
        }
        if (request.containsKey("projectType")) {
            project.setProjectType((String) request.get("projectType"));
        }
        if (request.containsKey("duration")) {
            project.setDuration((String) request.get("duration"));
        }
        if (request.containsKey("paymentRecord")) {
            project.setPaymentRecord((String) request.get("paymentRecord"));
        }
        if (request.containsKey("participants")) {
            project.setParticipants((String) request.get("participants"));
        }
        if (request.containsKey("projectLeader")) {
            project.setProjectLeader((String) request.get("projectLeader"));
        }
        if (request.containsKey("financialAccount")) {
            project.setFinancialAccount((String) request.get("financialAccount"));
        }
        if (request.containsKey("completionDate") && request.get("completionDate") != null) {
            project.setCompletionDate(LocalDate.parse((String) request.get("completionDate")));
        }
        
        verticalProjectRepository.update(project);
        return convertVerticalProjectToDto(project);
    }
    
    private Map<String, Object> updateHorizontalProject(Integer id, Map<String, Object> request, Integer userId) {
        HorizontalProject project = horizontalProjectRepository.findById(id);
        if (project == null) {
            throw new RuntimeException("横向课题不存在");
        }
        if (!project.getCreator().getId().equals(userId)) {
            throw new RuntimeException("无权修改他人的成果");
        }
        if (!"pending".equals(project.getApprovalStatus())) {
            throw new RuntimeException("只有待审核状态的成果才能修改");
        }
        
        // 更新字段
        if (request.containsKey("title")) {
            project.setProjectName((String) request.get("title"));
        }
        if (request.containsKey("contractNumber")) {
            project.setContractNumber((String) request.get("contractNumber"));
        }
        if (request.containsKey("contractAmount") && request.get("contractAmount") != null) {
            project.setContractAmount(new BigDecimal(request.get("contractAmount").toString()));
        }
        if (request.containsKey("clientName")) {
            project.setClientName((String) request.get("clientName"));
        }
        if (request.containsKey("projectLeader")) {
            project.setProjectLeader((String) request.get("projectLeader"));
        }
        if (request.containsKey("executiveLeader")) {
            project.setExecutiveLeader((String) request.get("executiveLeader"));
        }
        if (request.containsKey("duration")) {
            project.setDuration((String) request.get("duration"));
        }
        if (request.containsKey("paymentRecord")) {
            project.setPaymentRecord((String) request.get("paymentRecord"));
        }
        if (request.containsKey("participants")) {
            project.setParticipants((String) request.get("participants"));
        }
        if (request.containsKey("financialAccount")) {
            project.setFinancialAccount((String) request.get("financialAccount"));
        }
        if (request.containsKey("completionDate") && request.get("completionDate") != null) {
            project.setCompletionDate(LocalDate.parse((String) request.get("completionDate")));
        }
        
        horizontalProjectRepository.update(project);
        return convertHorizontalProjectToDto(project);
    }
    
    /**
     * 审核成果（教师端）
     */
    @PutMapping("/{type}/{id}/review")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> reviewAchievement(@PathVariable String type, @PathVariable Integer id, 
                                             @RequestBody Map<String, Object> request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        User reviewer = userService.findById(userDetails.getId());
        if (reviewer == null) {
            return ResponseEntity.badRequest().body(Map.of("message", "用户信息不存在"));
        }
        
        String status = (String) request.get("status");
        String comment = (String) request.get("comment");
        
        if (!"approved".equals(status) && !"rejected".equals(status)) {
            return ResponseEntity.badRequest().body(Map.of("message", "无效的审核状态"));
        }
        
        try {
            switch (type) {
                case "论文":
                    Paper paper = paperRepository.findById(id);
                    if (paper == null) {
                        return ResponseEntity.notFound().build();
                    }
                    if (!"pending".equals(paper.getApprovalStatus())) {
                        return ResponseEntity.badRequest()
                            .body(Map.of("message", "只有待审核状态的成果才能审核"));
                    }
                    paper.setApprovalStatus(status);
                    paper.setApprovalComment(comment);
                    paper.setApprover(reviewer);
                    paperRepository.update(paper);
                    break;
                case "纵向课题":
                    VerticalProject verticalProject = verticalProjectRepository.findById(id);
                    if (verticalProject == null) {
                        return ResponseEntity.notFound().build();
                    }
                    if (!"pending".equals(verticalProject.getApprovalStatus())) {
                        return ResponseEntity.badRequest()
                            .body(Map.of("message", "只有待审核状态的成果才能审核"));
                    }
                    verticalProject.setApprovalStatus(status);
                    verticalProject.setApprovalComment(comment);
                    verticalProject.setApprover(reviewer);
                    verticalProjectRepository.update(verticalProject);
                    break;
                case "横向课题":
                    HorizontalProject horizontalProject = horizontalProjectRepository.findById(id);
                    if (horizontalProject == null) {
                        return ResponseEntity.notFound().build();
                    }
                    if (!"pending".equals(horizontalProject.getApprovalStatus())) {
                        return ResponseEntity.badRequest()
                            .body(Map.of("message", "只有待审核状态的成果才能审核"));
                    }
                    horizontalProject.setApprovalStatus(status);
                    horizontalProject.setApprovalComment(comment);
                    horizontalProject.setApprover(reviewer);
                    horizontalProjectRepository.update(horizontalProject);
                    break;
                default:
                    return ResponseEntity.badRequest().body(Map.of("message", "不支持的成果类型"));
            }
            
            return ResponseEntity.ok(Map.of("message", "审核成功"));
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("message", "审核失败: " + e.getMessage()));
        }
    }
} 